<template>
  <view v-if="selectType === 'select'">
    <u-select
      v-if="feild !== 'professionType'"
      v-model="show"
      :list="list"
      :value-name="defaultProps?.value || 'value'"
      :label-name="defaultProps?.label || 'label'"
      :default-value="defaultValue"
      :safe-area-inset-bottom="true"
      @confirm="confirm"
    ></u-select>
    <zhilin-cascader
      v-else
      :value="show"
      :options="list"
      :defaultSelected="
        defaultValue && defaultValue[0] ? defaultValue[0].split(',') : []
      "
      @confirm="confirm"
      @input="(e:boolean) => (show = e)"
    >
    </zhilin-cascader>
  </view>
  <view v-else>
    <u-picker
      v-model="show"
      mode="time"
      :default-time="defaultValue"
      @confirm="confirm"
      :safe-area-inset-bottom="true"
    ></u-picker>
  </view>
</template>
<script lang="ts" setup>
import { updateCurrUser } from '@/api/modules/user';
import zhilinCascader from '@/components/zhilin-cascader/zhilin-cascader.vue';
import { valueType, CascaderOptions } from '../data';
import { getLabel } from '../index';

const emits = defineEmits(['submit']);

const props = defineProps<{
  info: any;
}>();
const { info } = toRefs(props);

const list = ref<any[]>();
const show = ref(false);
const feild = ref('');
const selectType = ref('');
const defaultValue = ref();
const defaultProps = ref();

const showSelect = (
  dataList: any[],
  feildName: string,
  type = 'select',
  value: any,
  props: any
) => {
  show.value = true;
  list.value = dataList;
  feild.value = feildName;
  selectType.value = type;
  defaultValue.value =
    Array.isArray(value) || type === 'picker' ? value : [value];
  defaultProps.value = props;
  console.log(defaultValue.value);
};
const confirm = (val: any) => {
  if (
    ['birthday', 'startDate', 'endDate', 'periodValidity'].includes(feild.value)
  ) {
    const { year, month, day } = val;
    info.value[feild.value] = `${year}-${month}-${day}`;
  } else {
    let value = '';
    if (feild.value === 'professionType') {
      value = val.join(',');
    } else {
      value = val[0].value;
    }
    info.value[feild.value] = value;
    if (feild.value in valueType) {
      if (feild.value !== 'professionType') {
        const key = valueType[feild.value];
        info.value[key] = val[0].label;
      }
    }
  }
  if ('professionType' in info.value) {
    const labelArr: (string | undefined)[] = [];
    let professionTypeValue =
      feild.value !== 'professionType'
        ? info.value.professionType.split(',')
        : val;
    const label = getLabel(CascaderOptions as any[], professionTypeValue);
    labelArr.push(label);
    const key = valueType.professionType;
    info.value[key] = labelArr.join(',');
  }
  emits('submit', info.value);
  show.value = false;
};
defineExpose({
  showSelect,
});
</script>
